package dataaccess;

import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class DataAccess {

    private String database;
    private String user;
    private String pass;
    private Connection con = null;

    public DataAccess() {
                    
        database = "DbTrieuPhu";
        user = "sa";
        pass = "123456";
                      
        String url = "jdbc:sqlserver://localhost:1433;databaseName=" + database + ";";
        try {
            
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            con = DriverManager.getConnection(url, user, pass);
           // System.out.println("Ket noi thanh cong");
        } catch (Exception e) {
            System.out.println("Ko ket noi dc");
            e.printStackTrace();
        }
    }

    public ResultSet executeProc(String procName, String[] args) {
        try {
            CallableStatement cs;
            if (args == null) {
                cs = con.prepareCall("{call" + procName + "}");
            } else {
                String sArg = "";
                int n = args.length;
                int i;
                for (i = 0; i < n; i++) {
                    sArg += args[i];
                    if (i != n - 1) {
                        sArg += ",";
                    }
                }
                cs = con.prepareCall("{call " + procName + "(" + sArg + ")}");
            }
            return cs.executeQuery();
        } catch (SQLException ex) {
            Logger.getLogger(DataAccess.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }

    public void executeProcVoid(String procName, String[] args) {
        try {
            CallableStatement cs;
            if (args == null) {
                cs = con.prepareCall("{call" + procName + "}");
            } else {
                String sArg = "";
                int n = args.length;
                int i;
                for (i = 0; i < n; i++) {
                    sArg += args[i];
                    if (i != n - 1) {
                        sArg += ",";
                    }
                }
                cs = con.prepareCall("{call " + procName + "(" + sArg + ")}");
                cs.execute();
            }
        } catch (SQLException ex) {
            Logger.getLogger(DataAccess.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void executeProc(String procName) {
        executeProc(procName, null);
    }
/*
    public static void main(String[] args) {
        new DataAccess();
    }
    */
}
